import {
  Component,
  OnInit,
  ViewEncapsulation,
  Injector,
  ViewChild
} from "@angular/core";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { AppComponentBase } from "@shared/common/app-component-base";
import { LazyLoadEvent } from "primeng/api";
import { Table } from "primeng/table";
import { Paginator } from "primeng/primeng";
import {
  BatchTaskServiceProxy,
  ConfirmDeliveryInput
} from "@shared/service-proxies/service-proxies";
import { finalize } from "rxjs/operators";

@Component({
  templateUrl: "./delivery-tasks.component.html",
  encapsulation: ViewEncapsulation.None,
  animations: [appModuleAnimation()]
})
export class DeliveryTasksComponent extends AppComponentBase implements OnInit {
  @ViewChild("dataTable") dataTable: Table;
  @ViewChild("paginator") paginator: Paginator;

  advancedFiltersAreShown = false;
  filterText = "";

  isReceived = false;

  tabs = [];

  constructor(
    injector: Injector,
    private _batchService: BatchTaskServiceProxy
  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.tabs = [
      { label: "未签收", value: false, icon: "fa fa-fw fa-calendar" },
      { label: "已签收", value: true, icon: "fa fa-fw fa-bar-chart" }
    ];
  }

  tabTypeClick(isReceived: boolean) {
    this.isReceived = isReceived;

    this.getDeliveryRecords();
  }

  getDeliveryRecords(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);

      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._batchService
      .getDeliveryRecords(
        this.filterText,
        undefined,
        53,
        this.isReceived,
        this.primengTableHelper.getSorting(this.dataTable),
        this.primengTableHelper.getSkipCount(this.paginator, event),
        this.primengTableHelper.getMaxResultCount(this.paginator, event)
      )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  confirm(record: number) {
    let self = this;

    this.message.confirm("确认签收改交接单吗？", isConfirm => {
      if (isConfirm) {
        let input = new ConfirmDeliveryInput();
        input.id = record;
        this._batchService
          .confirmDelivery(input)
          .pipe(finalize(() => {}))
          .subscribe(result => {
            self.notify.success("签收交接单成功");
            self.getDeliveryRecords();
          });
      }
    });
  }
}
